package aisino

import (
	"fmt"

	"gitee.com/xntk2381/invoice"
	"github.com/go-ole/go-ole/oleutil"
)

func (a *AisinoInvoice) ChaXun(kind int16) (stock *invoice.InvoiceStock, err error) {
	var (
		retCode int16
		retMsg  string
	)
	err = a.Init()
	if err != nil {
		return
	}
	defer func() {
		a.Release()
	}()

	fmt.Printf("设置属性 %v：%v\n", "InfoKind", kind)
	a.tax.PutProperty("InfoKind", kind)

	// 查询库存
	_, err = a.tax.CallMethod("GetInfo")
	if err != nil {
		return
	}
	retCode = oleutil.MustGetProperty(a.tax, "RetCode").Value().(int16)
	retMsg = oleutil.MustGetProperty(a.tax, "RetMsg").Value().(string)
	if retCode != 3011 {
		return nil, fmt.Errorf("RetCode=%v RetMsg=%v", retCode, retMsg)
	}

	fph := oleutil.MustGetProperty(a.tax, "InfoNumber").Value().(int32)
	number := fmt.Sprintf("%08d", fph)
	typeCode := oleutil.MustGetProperty(a.tax, "InfoTypeCode").Value().(string) // 发票代码
	if typeCode == "0000000000" {
		return nil, fmt.Errorf("无可用发票")
	}
	InvStock := oleutil.MustGetProperty(a.tax, "InvStock").Value()
	TaxClock := oleutil.MustGetProperty(a.tax, "TaxClock").Value()

	fmt.Printf("发票号：%v\n", number)
	fmt.Printf("发票代码：%v\n", typeCode)
	fmt.Printf("库存：%v\n", InvStock)
	fmt.Printf("时钟%v\n", TaxClock)
	stock = &invoice.InvoiceStock{
		TypeCode: typeCode,
		Number:   number,
		Stock:    InvStock,
		TaxClock: TaxClock,
	}

	return stock, nil
}
